<template>
  <el-card class="login-card">
    <h2 class="title">登录</h2>
    <el-form :model="form" ref="loginForm" label-position="top" status-icon>
      <el-form-item label="学号" prop="studentNo" :rules="[{ required: true, message: '请输入学号', trigger: 'blur' }]">
        <el-input v-model="form.studentNo" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
        <el-input v-model="form.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onLogin">登录</el-button>
        <el-button type="text" @click="$router.push('/register')">注册账号</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { reactive } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const form = reactive({
  studentNo: '',
  password: ''
});

const onLogin = async () => {
  if (!form.studentNo || !form.password) {
    ElMessage.error('请完整填写学号和密码');
    return;
  }
  try {
    const res = await axios.post('http://localhost:8081/api/students/login', form);
    ElMessage.success(res.data.message || '登录成功');

    // 假设后端返回的数据结构示例:
    // { id: 123, name: "张三", studentNo: "20200101", ... }

    const studentInfo = res.data;
    localStorage.setItem('studentInfo', JSON.stringify(studentInfo));
    localStorage.setItem('studentId', studentInfo.id);  // 这里确保存学生ID
    localStorage.setItem('loggedIn', 'true');

    window.location.href = '/test';
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '登录失败，请检查输入');
  }
};
</script>

<style scoped>
.login-card {
  max-width: 400px;
  margin: 100px auto;
  padding: 30px;
  border-radius: 8px;
}

.title {
  text-align: center;
  font-weight: 700;
  font-size: 24px;
  margin-bottom: 20px;
}
</style>
